package com.example.demo.service.homepage.impl;

import cn.hutool.core.map.MapUtil;
import com.example.demo.entity.CollectionName;
import com.example.demo.entity.exception.EnumException;
import com.example.demo.entity.exception.EnumResult;
import com.example.demo.service.comm.CommService;
import com.example.demo.service.homepage.BackStageService;
import com.example.demo.utils.StringUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
import org.bson.BsonDocument;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: cj
 * @create: 16-03-11 16:09:53
 */
@Service
public class BackStageServiceImpl implements BackStageService {
    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    CommService commService;
    @Resource
    MongoClient mongoClient;
    MongoDatabase database;

    @PostConstruct
    public void setDatabase() {
        database = mongoClient.getDatabase( "demo" );
    }

    /**
     * 设置首页数据 （简介，封面 等等）
     *
     * @param map 首页数据
     * @return 修改后的首页数据
     */
    @Override
    public Map<String, Object> update(Map<String, Object> map) {

        if (StringUtil.isEmpty( map.get( "_id" ) )) {
            throw new EnumException( EnumResult.EX_REQUEST_PAR_CODE );
        }
        if (map.containsKey( "loginUsers" )) {
            List<String> authors = (List<String>) map.get( "loginUsers" );
            if (!commService.isAuthor( authors )) {
                throw new EnumException( EnumResult.EX_USER_USER_TYPE_ERROR_CODE );
            }
        }

        map.put( "_id", new ObjectId( map.get( "_id" ).toString() ) );

        //修改 推荐文章
        if (map.containsKey( "shows" )) {
            List<String> shows = (List<String>) map.get( "shows" );
            List<ObjectId> objectIds = new ArrayList<>();
            shows.forEach( item -> {
                objectIds.add( new ObjectId( item ) );
            } );
            List<Map> mapList = mongoTemplate.find( Query.query( Criteria.where( "_id" ).in( shows ) ), Map.class, CollectionName.ESSAY );
            if (CollectionUtils.isEmpty( mapList ) || map.size() != shows.size()) {
                throw new EnumException( EnumResult.EX_ESSAY_NO_EXIST_CODE );
            }
            //首页id
            String id = map.get( "_id" ).toString();
            mongoTemplate.updateMulti( Query.query( Criteria.where( "_id" ).in( shows ) )
                    , Update.update( "show", id ), CollectionName.ESSAY );
            return null;
        }

        BasicDBObject query = new BasicDBObject( "_id", map.get( "_id" ) );
        BasicDBObject update = new BasicDBObject( map );
        database.getCollection( CollectionName.HOMEPAGE )
                .updateMany( query, new BasicDBObject( "$set", update ) );
        return map;
    }

    public void update(String collectionName, Map<String, Object> doc) {
        BasicDBObject queryObject = new BasicDBObject();
        queryObject.putAll( doc );
        try {
            BasicDBObject query = new BasicDBObject();
            ObjectId obId = new ObjectId( queryObject.get( "_id" ).toString() );
            queryObject.put( "_id", obId );
            query.put( "_id", new ObjectId( queryObject.get( "_id" ).toString() ) );
            database.getCollection( collectionName )
                    .updateMany( query, new BasicDBObject( "$set", queryObject ) );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
